<template>
	<view>
		<map style="width: 750rpx;height: 750rpx;" :longitude="longitude" :latitude="latitude" show-location
			@tap="handleMap" @poitap="handlePoi" :markers="markers" scale="10"></map>
			
		<uni-notice-bar show-icon text="点击地图任意位置，查看当地天气。" />

		<view class="content">
			<view class="title">今天天气</view>
			<view class="describe">更新时间：{{update_time}}</view>

			<view class="gregorian">
				<view>{{city}}</view>

				<view class="gregorianInfo">
					<view>{{weather}}</view>
					<image class="gregorianInfo-image" :src="getWeatherImage(weather)"></image>
				</view>

				<view class="gregorianInfo2">
					<view class="gregorian-temperature">{{temperature}}°</view>
				</view>

				<view class="gregorianInfo3">
					<view class="gregorianOther-bg">
						<image class="gregorianOther-image" src="/static/temperatureMin.png"></image>
						<view>
							<view class="gregorianOther-title">最低</view>
							<view>{{temperatureMin}}°</view>
						</view>

					</view>

					<view class="gregorianOther-bg">
						<image class="gregorianOther-image" src="/static/temperatureMax.png"></image>
						<view>
							<view class="gregorianOther-title">最高</view>
							<view>{{temperatureMax}}°</view>
						</view>

					</view>

					<view class="gregorianOther-bg">
						<image class="gregorianOther-image" src="/static/direction.png"></image>
						<view>
							<view class="gregorianOther-title">风向</view>
							<view>{{wind_direction}}</view>
						</view>
					</view>

					<view class="gregorianOther-bg">
						<image class="gregorianOther-image" src="/static/speed.png"></image>
						<view>
							<view class="gregorianOther-title">风力</view>
							<view>{{wind_power}}</view>
						</view>

					</view>
				</view>
			</view>
		</view>

		<view class="content">
			<view class="title">7天天气预报</view>

			<view class="gregorian">
				<view class="gregorianInfo" style="color: #333;" v-for="(item,index) in futureWeather" :key="index">
					<view>
						<view v-if="index==0">今天</view>
						<view v-else>{{item.week}}</view>
						<view class="describe">{{item.date}}</view>
					</view>


					<view style="display: flex;align-items: center;">
						<image class="gregorianInfo-image" :src="getWeatherImage(item.day.weather)"></image>
						<view style="margin-left: 20rpx;">{{item.night.temperature}}°</view>
						<view style="margin: 0 10rpx;">~</view>
						<view>{{item.day.temperature}}°</view>
					</view>
				</view>
			</view>
		</view>

		<view style="height: 1px;"></view>

		<popVerify2 ref="popRef" @success="verifySuccess"></popVerify2>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import {
		onLoad
	} from '@dcloudio/uni-app';

	const popRef = ref()
	const requestCount = ref(0) // 接口调用次数

	const city = ref('济南市') //中文：省市区
	const weather = ref('晴') //当前天气描述
	const temperature = ref('30') //当前温度
	const update_time = ref('2000-01-01 00:00:00') //更新时间

	const temperatureMin = ref('0') //今天最低温度
	const temperatureMax = ref('30') //今天最高温度
	const wind_direction = ref("西北风") //风向
	const wind_power = ref("3～4级") //风速
	const futureWeather = ref([]) // 未来7天
	// 默认经纬度
	const longitude = ref(117.20800815235214)
	const latitude = ref(36.665893695272715)
	const markers = ref([{
		id: 1,
		latitude: 36.665893695272715,
		longitude: 117.20800815235214,
		iconPath: '/static/location.png',
		width: 30,
		height: 30
	}])

	onLoad(() => {
		try {
			const value = uni.getStorageSync(uni.$uv.timeFormat(new Date(), "yyyy-mm-dd"));
			if (value) {
				requestCount.value = value
			}
		} catch (e) {
			console.log(e)
		}
		// 获取当前位置
		uni.getLocation({
			type: 'gcj02',
			// type: 'wgs84',
			success: function(res) {
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				longitude.value = res.longitude
				latitude.value = res.latitude
				markers.value = [{
					id: 1,
					latitude: latitude.value,
					longitude: longitude.value,
					iconPath: '/static/location.png',
					width: 30,
					height: 30
				}]
				getWeatherPre()
			}
		});
	})

	// 点击poi
	function handlePoi(e) {
		// console.log('handlePoi',e)
		longitude.value = e.detail.longitude
		latitude.value = e.detail.latitude
		markers.value = [{
			id: 1,
			latitude: latitude.value,
			longitude: longitude.value,
			iconPath: '/static/location.png',
			width: 30,
			height: 30
		}]
		getWeatherPre()
	}

	// 小程序能点
	function handleMap(e) {
		// console.log('handleMap', e.detail)
		longitude.value = e.detail.longitude
		latitude.value = e.detail.latitude
		markers.value = [{
			id: 1,
			latitude: latitude.value,
			longitude: longitude.value,
			iconPath: '/static/location.png',
			width: 30,
			height: 30
		}]
		// 验证
		getWeatherPre()
	}

	// 验证成功
	function verifySuccess() {
		getWheather()
	}

	// 获取天气前验证
	function getWeatherPre() {
		if (requestCount.value > getApp().globalData.weatherCount) {
			popRef.value.open()
		} else {
			getWheather()
		}
	}

	// 获取天气信息
	function getWheather() {
		requestCount.value = requestCount.value + 1
		try {
			uni.setStorageSync(uni.$uv.timeFormat(new Date(), "yyyy-mm-dd"), requestCount.value);
		} catch (e) {
			console.log(e)
		}

		uni.request({
			url: 'https://apis.map.qq.com/ws/weather/v1/', //仅为示例，并非真实接口地址。
			data: {
				key: '5BQBZ-IB3HB-PQKUU-NUN5H-EUFZ7-2IFLC',
				location: `${latitude.value},${longitude.value}`,
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				console.log(res.data);
				if (res.data.status == 0) {
					let realtime0 = res.data.result.realtime[0]
					update_time.value = realtime0.update_time
					city.value = realtime0.province + "/" + realtime0.city + "/" + realtime0.district

					weather.value = realtime0.infos.weather
					temperature.value = realtime0.infos.temperature
					wind_direction.value = realtime0.infos.wind_direction
					wind_power.value = realtime0.infos.wind_power

					forecast()
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "none"
					});
				}
			},
			fail: (err) => {
				uni.showToast({
					title: "接口调用失败",
					icon: "none"
				});
			}
		});
	}

	function forecast() {
		uni.request({
			url: 'https://apis.map.qq.com/ws/weather/v1/', //仅为示例，并非真实接口地址。
			data: {
				key: '5BQBZ-IB3HB-PQKUU-NUN5H-EUFZ7-2IFLC',
				location: `${latitude.value},${longitude.value}`,
				type: "future",
				get_md: "1"
			},
			success: (res) => {
				console.log(res.data);
				if (res.data.status == 0) {
					let forecast0 = res.data.result.forecast[0]
					futureWeather.value = forecast0.infos
					temperatureMax.value = forecast0.infos[0].day.temperature
					temperatureMin.value = forecast0.infos[0].night.temperature
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "none"
					});
				}
			},
			fail: (err) => {
				uni.showToast({
					title: "接口调用失败",
					icon: "none"
				});
			}
		});
	}

	function getWeatherImage(text) {
		// 检查文本中是否包含各种天气关键词
		const hasRain = text.includes('雨');
		const hasSnow = text.includes('雪');
		const hasSunny = text.includes('晴');
		const hasCloudy = text.includes('多云');

		// 优先检查雨雪组合
		if (hasRain && hasSnow) {
			return '/static/weather-yuXue.png';
		} else if (hasRain) {
			return '/static/weather-yu.png';
		} else if (hasSnow) {
			return '/static/weather-xue.png';
		} else if (hasSunny) {
			// 检查晴天
			return '/static/weather-qing.png';
		} else if (hasCloudy) {
			// 检查多云
			return '/static/weather-duoyun.png';
		} else {
			// 既不包含以上天气，返回默认图片
			return '/static/weather-duoyun.png';
		}
	}
</script>

<style>
	@import "weather.css"
</style>